﻿@using System.Text
@using System.IO
@using Blazorise.Docs.Models
<Paragraph>
    <Div Class="blog-page-section-source">
        <Div Class="blog-page-section-source-toolbar">
            <Tooltip Text="@(ShowCode ? "Hide code example" : "Show code example")" Inline>
                <Button Clicked="@OnToggleCode">
                    <Icon Name="IconName.Code" />
                </Button>
            </Tooltip>
            <Tooltip Text="Copy code" Inline>
                <Button Clicked="@OnCopyCode">
                    <Icon Name="@("fas fa-copy")" />
                </Button>
            </Tooltip>
        </Div>
        <Div Class="@SourceCodeClassNames">
            @CodeComponent( CurrentCode )
        </Div>
    </Div>
</Paragraph>
@code {
    protected override void OnInitialized()
    {
        CurrentCode = Code;
    }

    private Task OnToggleCode()
    {
        ShowCode = !ShowCode;

        return Task.CompletedTask;
    }

    private async Task OnCopyCode()
    {
        await JSRuntime.InvokeVoidAsync( "blazoriseDocs.code.copyToClipboard", Snippets.GetCode( Code ) );
        await NotificationService.Info( $"Copied code example!" );
    }

    private RenderFragment CodeComponent( string code ) => builder =>
    {
        try
        {
            var key = typeof( DocsPageSectionSource ).Assembly.GetManifestResourceNames().FirstOrDefault( x => x.Contains( $".{code}Code.html" ) );

            if ( key != null )
            {
                using var stream = typeof( DocsPageSectionSource ).Assembly.GetManifestResourceStream( key );
                using var reader = new StreamReader( stream );
                builder.AddMarkupContent( 0, reader.ReadToEnd() );
            }
        }
        catch ( Exception )
        {
        }
    };

    private string SourceCodeClassNames
    {
        get
        {
            var sb = new StringBuilder( "blog-page-section-source-code" );

            if ( ShowCode )
                sb.Append( " blog-page-section-source-code-show" );
            else
                sb.Append( " blog-page-section-source-code-hide" );

            return sb.ToString();
        }
    }

    private string CurrentCode { get; set; }

    private TextColor ButtonColor => ShowCode ? TextColor.White : TextColor.Dark;

    [Inject] public INotificationService NotificationService { get; set; }

    [Inject] public IJSRuntime JSRuntime { get; set; }

    [Parameter] public string Code { get; set; }

    [Parameter] public bool ShowCode { get; set; } = true;
}